/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="trafficStrength"
    v-loading="loading"
    element-loading-spinner="el-icon-loading"
    :element-loading-background="loadingBg">
    <div class="left">
      <div class="lefttop">
        <div class="title">{{$t('openatc.patternstatistic.patterninfo')}}</div>
          <div class="choosePanel">
            <span v-for="(item, index) in chooseButtons"
                  :key="index">
              <span v-on:click="()=>updateStrengthChart(item.key)"
                    class="btn"
                    :class="{'btnFocus': item.active === true}">{{item.value}}</span>
            </span>
          </div>
          <div class="chart1" id="strength"></div>
          <!-- <CurPhaseChart :TimingData="TimingData" :date="date" /> -->
      </div>
      <div class="leftbottom">
        <div class="title">{{$t('openatc.patternstatistic.historicalcurrphase')}}</div>
        <div class="chart2" style="display: none;" id="timing"></div>
        <CurPhaseChart :RealtimeHistoryPatternData="RealtimeHistoryPatternData" :date="date" :ASCID="ASCID" :phaseList="phaseList"/>
      </div>
    </div>
    <div class="right">
      <strengthPanel ref="strengthPanel"
                     :curChart="curChart"
                     :strengthdata="curStrengthData"
                     :strengthSelet="strengthSeleted"></strengthPanel>
      <!-- <periodicPanel ref="periodicPanel"
                     :rangdata="curTimeData"
                     :periodicSelet="periodicSeleted"></periodicPanel> -->
    </div>
  </div>
</template>
<script>
import * as echart from 'echarts'
import strengthPanel from './strengthPanel'
import periodicPanel from './periodicPanel'
import { getRealtimeHistoryPatternData } from '../../../../api/historydata.js'
import moment from 'moment'
import TrafficDataDecisionModel from './trafficDataDecision.js'
import { getTheme } from '../../../../utils/auth'
import { ExportHistoricalStatistics } from '../../../../utils/export.js'
import { getTscPhase } from '../../../../api/route'
import { getMessageByCode } from '../../../../utils/responseMessage.js'
import { images } from '../../../../utils/phaseList.js'
import CurPhaseChart from './curPhaseChart'
export default {
  name: 'detailed-trafficstrength',
  components: {
    strengthPanel,
    periodicPanel,
    CurPhaseChart
  },
  props: {
    date: {
      type: Array
    },
    ASCID: undefined
  },
  data () {
    return {
      curTimeData: {},
      curStrengthData: {},
      timeSelIndex: -1,
      strSelIndex: -1,
      loading: false,
      loadingBg: '#202940',
      chooseButtons: [
        {
          key: 'mode',
          value: this.$t('openatc.patternstatistic.controlmode'),
          active: true
        },
        {
          key: 'control',
          value: this.$t('openatc.patternstatistic.controltype'),
          active: false
        },
        {
          key: 'patternid',
          value: this.$t('openatc.patternstatistic.controlscheme'),
          active: false
        },
        {
          key: 'cycle',
          value: this.$t('openatc.patternstatistic.cycle'),
          active: false
        },
        {
          key: 'patternoffset',
          value: this.$t('openatc.patternstatistic.phasedifference'),
          active: false
        },
        {
          key: 'syncTime',
          value: this.$t('openatc.patternstatistic.synctime'),
          active: false
        },
        {
          key: 'curTime',
          value: this.$t('openatc.patternstatistic.coordinationtime'),
          active: false
        }
      ],
      curChart: {
        key: 'mode',
        value: this.$t('openatc.patternstatistic.controlmode')
      },
      periodicSeleted: undefined,
      strengthSeleted: undefined,
      Color: new Map([[0, '#43b4cf'], [1, '#c6bf72'], [2, '#5085d1'], [3, '#cc7966'], [4, '#537896'], [5, '#d39351'], [6, '#45ab89'], [7, '#a25768']]),
      DirectionMap: new Map(), // 当前设备的相位方向Map
      TimingData: undefined,
      phaseList: [],
      RealtimeHistoryPatternData: {}
    }
  },
  created () {
    this.setLoadingBg()
    this.getCurPhaseDirection()
  },
  mounted () {
    this.initChart()
    this.refreshChart()
  },
  methods: {
    setLoadingBg () {
      this.loadingBg = getTheme() === 'light' ? '#fff' : '#202940'
    },
    changeBtnStyle (key) {
      // 选中按钮高亮
      this.chooseButtons.forEach(button => {
        button.active = false
        if (button.key === key) {
          button.active = true
        }
      })
    },
    updateStrengthChart (key) {
      this.changeBtnStyle(key)
      // 更新相位分布环图小标题
      this.curChart = this.chooseButtons.filter(btn => btn.key === key)[0]
      const curData = this.decisionModel.getData(key)
      this.strengthData = curData
      this.renderStrengthChart()
    },
    lockScreen () {
      this.loading = true
    },
    unlockScreen () {
      this.loading = false
    },
    initChart () {
      this.strengthChart = echart.init(document.getElementById('strength'))
      this.timingChart = echart.init(document.getElementById('timing'))
      this.InitStrengthChartEvent()
      this.InitTimeChartEvent()
      const _this = this
      window.onresize = function () {
        _this.strengthChart.resize()
        _this.timingChart.resize()
      }
    },
    ShowPanelStrength (selIndex) {
      if (this.strengthData === undefined || selIndex === undefined) return
      this.curStrengthData = this.alldata[selIndex]
    },
    ShowPanelRang (selIndex) {
      if (this.TimingData === undefined ||
      this.$refs.periodicPanel === undefined || selIndex === undefined) return
      this.curTimeData = this.TimingData[selIndex]
      this.$refs.periodicPanel.refreshRangChart()
    },
    InitStrengthChartEvent () {
      this.strengthChart.on('updateAxisPointer', event => {
        this.ShowPanelStrength(event.dataIndex)
      })

      this.strengthChart.on('click', event => {
        if (this.strengthData === undefined) return
        this.timingChart.dispatchAction({
          type: 'downplay',
          dataIndex: this.timeSelIndex
        })
        this.timeSelIndex = this.findIndexInTimeData(event.name)
        this.timingChart.dispatchAction({
          type: 'highlight',
          dataIndex: this.timeSelIndex
        })

        this.ShowPanelRang(this.timeSelIndex)
      })

      this.strengthChart.on('legendselectchanged', event => {
        // 点击图例取消某相位显示，对应的相位分布图也要取消该相位
        this.strengthSeleted = event.selected
      })
    },
    InitTimeChartEvent () {
      this.timingChart.on('updateAxisPointer', event => {
        this.ShowPanelRang(event.dataIndex)
      })

      this.timingChart.on('click', event => {
        if (this.TimingData === undefined) return
        this.curTimeData = this.TimingData[event.dataIndex]

        this.timingChart.dispatchAction({
          type: 'downplay',
          dataIndex: this.timeSelIndex
        })

        let date = event.name
        this.strengthChart.dispatchAction({
          type: 'downplay',
          dataIndex: this.strSelIndex
        })
        this.strSelIndex = this.findIndexInStrengthData(date)
        this.strengthChart.dispatchAction({
          type: 'highlight',
          dataIndex: this.strSelIndex
        })

        this.ShowPanelStrength(this.strSelIndex)
      })
      this.timingChart.on('legendselectchanged', event => {
        // 点击图例取消某相位显示，对应的周期分布图也要取消该相位
        this.periodicSeleted = event.selected
      })
    },
    findIndexInTimeData (date) {
      let XAxisList = this.getTimingXAxis(this.TimingData)
      // XAxisList = XAxisList.sort((val1, val2) => {
      //   return new Date(val1).getTime() > new Date(val2).getTime()
      // })
      for (let index = XAxisList.length - 1; index >= 0; --index) {
        let strDate = new Date(date)
        let timeDate = new Date(XAxisList[index])
        if (timeDate.getTime() < strDate.getTime()) { return index - 1 }
      }
      return -1
    },
    findIndexInStrengthData (date) {
      let XAxisList = this.getStrXAxis(this.strengthData)
      for (let index = 0; index < XAxisList.length; ++index) {
        let timeDate = new Date(date)
        let strDate = new Date(XAxisList[index])
        if (timeDate.getTime() < strDate.getTime()) { return index }
      }

      return -1
    },
    async refreshChart () {
      this.lockScreen()
      await this.getRealtimeHistoryPattern()
      this.refreshStrengthChart()
      this.refreshTimingChart()
      this.unlockScreen()
      this.changeBtnStyle('mode')
    },
    renderStrengthChart () {
      // 渲染
      if (this.strengthData.length === 0) {
        this.strengthChart.clear()
        return
      }
      // 取最新时刻的相位数据，赋值给curStrengthData
      this.curStrengthData = this.alldata[this.alldata.length - 1]
      let strOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false
          },
          formatter: function (params) {
            if (params[0].seriesName === 'anchor') {
              return ''
            }
            var text = '--'
            if (params && params.length) {
              text = params[0].data[0] // 提示框顶部的日期标题
              params.forEach(item => {
                const dotHtml = item.marker // 提示框示例的小圆圈,可以在这里修改
                text += `</br>${dotHtml}${item.seriesName} : ${item.data[1] !== null ? item.data[1] : '-'}`
              })
            }
            return text
          }
        },
        grid: {
          containLabel: true,
          height: '80%',
          width: '93%',
          right: '45',
          bottom: '5'
        },
        xAxis: {
          type: 'time',
          boundaryGap: false,
          axisLabel: {
            rotate: '8',
            margin: 20,
            align: 'center',
            textStyle: {
              color: getTheme() === 'light' ? '#666666' : '#B9BABF'
            },
            formatter: function (value, i) { // 坐标轴文字展示样式处理
              // if (i > 1) {
              //   return echart.format.formatTime('MM-dd hh:mm:ss', value)
              // } else {
              //   return ''
              // }
              return echart.format.formatTime('hh:mm:ss', value)
            }
          },
          axisTick: {
            show: true,
            length: 6,
            alignWithLabel: true,
            lineStyle: {
              // width: 2,
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          },
          axisLine: {
            lineStyle: {
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          }
        },
        yAxis: {
          axisTick: {
            lineStyle: {
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          },
          axisLine: {
            lineStyle: {
              color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
            }
          },
          splitLine: {
            lineStyle: {
              color: getTheme() === 'light' ? '#DCDFE6' : '#30384d'
            }
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: getTheme() === 'light' ? ['#fafafa', '#fff'] : ['#202940', '#1a2338']
            }
          },
          axisLabel: {
            textStyle: {
              color: getTheme() === 'light' ? '#666666' : '#B9BABF'
            }
          }
        },
        series: [this.getStrSeries(this.strengthData), this.getLineAnchorSeries()]
      }
      this.strengthChart.setOption(strOption)
    },
    refreshStrengthChart () {
      return this.getStrengthData().then(data => {
        this.alldata = JSON.parse(JSON.stringify(data))
        this.decisionModel = new TrafficDataDecisionModel(data)
        const curData = this.decisionModel.getData('mode')
        this.strengthData = curData
        this.renderStrengthChart()
      })
    },
    getStrXAxis (dataList) {
      let xAxisList = []
      for (let data of dataList) {
        xAxisList = [...xAxisList, data.date]
      }
      return [...new Set(xAxisList)]
    },
    getStrSeries (dataList) {
      let series = {
        name: this.curChart.value,
        type: 'line',
        connectNulls: true,
        itemStyle: {
          color: '#75B1E6'
        },
        // areaStyle: {
        //   normal: {
        //     color: new echart.graphic.LinearGradient(
        //       0, 0, 0, 1,
        //       [
        //         {offset: 0, color: '#77b3e8'},
        //         {offset: 0.2, color: '#7cb5e9'},
        //         {offset: 0.4, color: '#95c5ed'},
        //         {offset: 0.6, color: '#b1d3f1'},
        //         {offset: 0.8, color: '#c9e0f5'},
        //         {offset: 1, color: '#cee3f6'}
        //       ]
        //     ) // 区域的颜色
        //   }
        // }
        showSymbol: false
      }
      series.data = dataList.map(item => {
        return [item.date, item.value]
      })
      return series
    },
    getLineAnchorSeries () {
      let anchor = [
        [moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss'), 0],
        [moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss'), 0]
      ]
      let anchorSeries = {
        name: 'anchor',
        type: 'line',
        showSymbol: false,
        data: anchor,
        itemStyle: {normal: {opacity: 0}},
        lineStyle: {normal: {opacity: 0}}
      }
      return anchorSeries
    },
    refreshTimingChart () {
      return this.getTimingData().then(data => {
        this.TimingData = data
        if (this.TimingData.length === 0) {
          this.timingChart.clear()
          return
        }
        this.curTimeData = data[data.length - 1]
        let _this = this
        let strOption = {
          tooltip: {
            trigger: 'axis',
            // triggerOn: 'click',
            // alwaysShowContent: true,
            axisPointer: {
              animation: false
            },
            formatter: function (params) {
              if (params[0].seriesName === 'anchor') {
                return ''
              }
              let tooltipstr = ''
              if (params && params.length) {
                let rangstr = ''
                // let createtime = _this.$t('openatc.patternstatistic.time')
                let rang = _this.$t('openatc.patternstatistic.rang')
                let direction = _this.$t('openatc.patternstatistic.direction')
                let phaseid = _this.$t('openatc.patternstatistic.phaseid')
                for (let i = 0; i < params.length; i++) {
                  const dotHtml = params[i].marker // 提示框示例的小圆圈,可以在这里修改
                  let onephase = `<div>
                    <div class="tooltiplabel">${dotHtml}${rang}${params[i].value[2].ring}:</div>
                    <div><span class="tooltiplabel">${phaseid}</span>${params[i].value[1]}</div>`
                  if (params[i].value[2]) {
                    onephase = onephase + `<div><span class="tooltiplabel">${direction}</span>${params[i].value[2].dirname}</div>`
                  }
                  onephase = onephase + `</div>`
                  rangstr = rangstr + onephase
                }
                tooltipstr = `
                  <div class="timing-tooltip">
                    <div><span>${params[0].value[0]}</span></div>
                    <div>${rangstr}</div>
                  </div>`
              }
              return tooltipstr
            }
          },
          grid: {
            containLabel: true,
            height: '80%',
            width: '93%',
            right: '45',
            bottom: '5'
          },
          legend: {
            right: 100,
            textStyle: {
              color: getTheme() === 'light' ? '#666666' : '#B9BABF'
            },
            data: this.getTimingLegend(this.TimingData)
          },
          xAxis: {
            type: 'time',
            axisTick: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLabel: {
              rotate: '8',
              margin: 20,
              align: 'center',
              textStyle: {
                color: getTheme() === 'light' ? '#666666' : '#B9BABF'
              },
              formatter: function (value, index) { // 坐标轴文字展示样式处理
                return echart.format.formatTime('MM-dd hh:mm:ss', value)
              }
            }
          },
          yAxis: {
            axisTick: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLabel: {
              textStyle: {
                color: getTheme() === 'light' ? '#666666' : '#B9BABF'
              }
            },
            splitLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#DCDFE6' : '#30384d'
              }
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: getTheme() === 'light' ? ['#fafafa', '#fff'] : ['#202940', '#1a2338']
              }
            }
          },
          series: [...this.getTimingSeries(this.TimingData), this.getLineAnchorSeries()]
        }
        this.timingChart.setOption(strOption)
      })
    },
    getTimingLegend (dataList) {
      let lergeList = []

      for (let data of dataList) {
        let rang1Data
        if (data.rang1) {
          rang1Data = data.rang1.map(item => {
            return this.$t('openatc.patternstatistic.rang') + item.ring
          })
          lergeList = [...lergeList, ...rang1Data]
        }
        let rang2Data
        if (data.rang2) {
          rang2Data = data.rang2.map(item => {
            return this.$t('openatc.patternstatistic.rang') + item.ring
          })
          lergeList = [...lergeList, ...rang2Data]
        }
      }
      return [...new Set(lergeList)]
    },
    getTimingXAxis (dataList) {
      return dataList.map(item => {
        return item.date
      })
    },
    getTimingSeries (dataList) {
      let series = []
      let rang1data = []
      let rang2data = []
      for (let data of dataList) {
        let date = data.date
        if (data.rang1) {
          for (let i = 0; i < data.rang1.length; i++) {
            let phase = data.rang1[i]
            let direction = phase.direction
            let dirname = ''
            if (direction) {
              dirname = this.getPhaseName(direction).name
            }
            rang1data.push([date, phase.phaseid, {
              ...phase,
              dirname
            }])
          }
        }
        if (data.rang2) {
          for (let i = 0; i < data.rang2.length; i++) {
            let phase = data.rang2[i]
            let direction = phase.direction
            let dirname = ''
            if (direction) {
              dirname = this.getPhaseName(direction).name
            }
            rang2data.push([date, phase.phaseid, {
              ...phase,
              dirname
            }])
          }
        }
      }
      if (rang1data.length) {
        series.push({
          name: this.$t('openatc.patternstatistic.rang') + rang1data[0][2].ring,
          type: 'line',
          connectNulls: true,
          itemStyle: {
            color: this.Color.get(0)
          },
          showSymbol: false,
          data: rang1data
        })
      }
      if (rang2data.length) {
        series.push({
          name: this.$t('openatc.patternstatistic.rang') + rang2data[0][2].ring,
          type: 'line',
          connectNulls: true,
          itemStyle: {
            color: this.Color.get(1)
          },
          showSymbol: false,
          data: rang2data
        })
      }
      return series
    },
    getRealtimeHistoryPattern () {
      let params = {
        beginTime: moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss'),
        agentId: this.ASCID
      }
      return new Promise((resolve, reject) => {
        getRealtimeHistoryPatternData(params).then(res => {
          if (!res.data.success) {
            this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
            reject(res.data.message)
          }
          this.RealtimeHistoryPatternData = res
          resolve()
        }).catch(() => {
          console.log('getRealtimeHistoryPatternData error')
          this.unlockScreen()
        })
      })
    },
    getStrengthData () {
      return new Promise((resolve, reject) => {
        let res = JSON.parse(JSON.stringify(this.RealtimeHistoryPatternData))
        let resData = []
        for (let data of res.data.data) {
          let date = moment(data['time']).format('YYYY-MM-DD HH:mm:ss')
          let phaseData = {
            date,
            mode: data.data.mode,
            control: data.data.control,
            patternid: data.data.patternid,
            cycle: data.data.cycle,
            patternoffset: data.data.patternoffset,
            syncTime: data.data.syncTime,
            curTime: data.data.curTime,
            currentPhase: data.data.current_phase
          }
          resData.push(phaseData)
        }
        resolve(resData)
      })
    },

    getRingId (phaseId, ringList) {
      let ringNum = -1
      for (let ringInfo of ringList) {
        if (ringInfo.sequence.indexOf(phaseId) > -1) {
          ringNum = ringInfo.num
          break
        }
      }

      return ringNum
    },

    getTimingData () {
      return new Promise((resolve, reject) => {
        let res = JSON.parse(JSON.stringify(this.RealtimeHistoryPatternData))
        let resData = []
        let resData2 = []
        for (let data of res.data.data) {
          let curTime = moment(data['time']).format('YYYY-MM-DD HH:mm:ss')
          let timeData = resData.find(val => curTime === val.date)
          if (timeData === undefined) {
            timeData = {
              date: curTime
            }
            resData2.push(timeData)
          }
          if (data.data.current_phase) {
            data.data.current_phase.forEach((curphase, index) => {
              if (curphase !== undefined) {
              // 过滤设备相位里不包含的当前相位数据
                let info = {
                  date: curTime,
                  phasename: '相位' + curphase,
                  phaseid: curphase
                }
                if (this.DirectionMap.get(curphase)) {
                  info.ring = this.DirectionMap.get(curphase).ring
                  info.direction = this.DirectionMap.get(curphase).direction
                  resData.push(info)
                }
              }
            })
          }
        }
        for (let data of resData2) {
          resData.forEach(ele => {
            if (ele.date === data.date) {
              let ring = ele.ring
              if (ring) {
                if (!data[`rang${ring}`]) {
                  data[`rang${ring}`] = [ele]
                } else {
                  data[`rang${ring}`].push(ele)
                }
              } else {
                // ring不存在当1
                if (!data[`rang1`]) {
                  data[`rang1`] = [ele]
                } else {
                  data[`rang1`].push(ele)
                }
              }
            }
          })
        }
        resolve(resData2)
      })
    },

    exportHistoricalData (crossName) {
      let exportarr = []
      if (this.RealtimeHistoryPatternData.data && this.RealtimeHistoryPatternData.data.data.length) {
        exportarr = this.RealtimeHistoryPatternData.data.data.map(hisdata => {
          let exportfield = {
            '时间': moment(hisdata.time).format('YYYY-MM-DD HH:mm:ss'),
            '方案编号': hisdata.data.patternid,
            '控制模式': hisdata.data.mode,
            '控制方式': hisdata.data.control,
            '周期': hisdata.data.cycle,
            '相位差': hisdata.data.patternoffset
          }
          if (hisdata.data.phase) {
            for (let j = 0; j < hisdata.data.phase.length; j++) {
              let curphase = hisdata.data.phase[j]
              exportfield[`相位${curphase.id}`] = curphase.split
            }
          }
          return exportfield
        })
        // let headerorder = ['时间', '方案编号', '控制模式', '控制方式', '周期', '相位差']
        let headerorder = []
        ExportHistoricalStatistics(exportarr, `${crossName}历史方案统计数据.xlsx`, headerorder, `${crossName}历史运行信息`)
      }
    },
    getCurPhaseDirection () {
      getTscPhase(this.ASCID).then(res => {
        if (!res.data.success) {
          if (res.data.code === '4003') {
            this.$message.error(this.$t('openatc.common.devicenotonline'))
            return
          }
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        if (!res.data.data.data.phaseList) return
        this.phaseList = res.data.data.data.phaseList
        res.data.data.data.phaseList.map(ele => {
          this.DirectionMap.set(ele.id, {...ele})
        })
        console.log(this.DirectionMap)
      })
    },
    getName (status) {
      let name = ''
      for (let i = 0; i < status.length; i++) {
        if (!status[i]) continue
        name = name + ',' + this.$t(images[i].name)
      }
      if (name !== '') {
        const obj = {
          name: name.substr(1)
        }
        return obj
      } else {
        return {
          name: ''
        }
      }
    },
    getPhaseName (desc) {
      // 根据相位描述数组得到相位名称
      let status = []
      for (let obj of images) {
        if (desc.length > 0 && desc.includes(obj.id)) {
          status.push(1)
        } else {
          status.push(0)
        }
      }
      return this.getName(status)
    }
  }
}
</script>
